// 验证 _activePageURL是否 bindMobile可取到值
// bindMobile 跳转参数fromApp
let _app,_activePageURL = null;
async function unfinishedTaskFn(data,app) {
  _app = app;
  let _href = getRouteData();
  let _isMissionURL = _href === 'packageG/missionCenter/missionCenter'; //是否位于任务中心页
  _activePageURL = !_isMissionURL ? _href : _app.globalData.beforeBindMobilePage || _href;

  const promises = [
    bindMobile(data),
    bindInviter(data),
    bindRealName(data),
    setAddress(data),
    uploadVideo(data),
    levelCompel(data),
    phoneBillRecharge(data),
    signContract(data)
  ];
  const results = await Promise.allSettled(promises); //并行执行，并返回包含所有承诺结果的对象数组
  let validResults = [];//当前符合条件的集合
  let activeResults = [];//当前符合条件并且处于某个条件处理的页面内，不做处理
  console.log(validResults,activeResults)

  for (let i = 0; i < results.length; i++) {
    const result = results[i];
    if(result.status === "rejected" && result.reason.type) {
      if (result.reason.type == 'active') {
        activeResults.push(result);
      } else {
        validResults.push(result);
      }
    }
  }

  if(validResults.length === 0 && activeResults.length === 0) {
    if(_href === 'packageG/missionCenter/missionCenter') {
     // 新装修数据
      wx.removeStorageSync("home_onUnload");
      wx.removeStorageSync("new_decorate");
      wx.reLaunch({
        url: _activePageURL
      })
    }
    return;
  }

  if(_isMissionURL || activeResults.length > 0) {
    return validResults;//当前处理任务中心页或者某个条件的页面内，return处理
  }

  if (validResults.length >= 2) {
    if(!_isMissionURL){
      if(activeResults.length === 0){
        let _sURL = _app.globalData.beforeBindMobilePage ||null;
        if(!_sURL) _app.setBeforeBindMobilePage();//记录绑定手机跳转前页面路径
      }
      // 清空新装修数据 
      wx.removeStorageSync("home_onUnload");
      wx.removeStorageSync("new_decorate");
      wx.reLaunch({
        url: '/packageG/missionCenter/missionCenter'//如果有两个或两个以上promist符合条件，则执行跳转到 任务中心列表页：
      })
    }
    return validResults;
  }
  _app.setBeforeBindMobilePage();
  validResults.forEach((result) => {
    redirectToPage(result.reason);
  });
}
function redirectToPage(result) {
  let {type, extinfo} = result;
  let _href = getRouteData();
  let _isMissionURL = _href === 'packageG/missionCenter/missionCenter'; //是否位于任务中心页
  _activePageURL = !_isMissionURL ? _href : _app.globalData.beforeBindMobilePage || _href;
  let callbackUrl = '';
  let validate_page = wx.getStorageSync('validate_page');
  let path;
  switch (type) {
  case "bindMobile":
    path = '/packageA/member/editmobile/editmobile';
    break;
  case "bindInviter":
    path = '/packageC/member/visit/Inviter/Inviter';
    break;
  case "bindRealName":
    path = '/packageH/signPage/personBank/personBank';
    break;
  case "setAddress":
    return wx.showModal({
      title:'请设置默认地址',
      content:'',
      showCancel:false,
      confirmText:'去设置',
      success(res){
        wx.redirectTo({
          url: "/packageD/member/addressList/addressList",
        }); 
      }
    })
    break;
  case "uploadVideo":
    path = '/packageC/video_goods/releaseVideo/releaseVideo';
    break;
  case "levelCompel":
    path = '/packageJ/levelCompel/levelCompel';
    break;
  case "phoneBillRecharge":
    return wx.showModal({
      content: extinfo.content,
      complete: (res) => {
        _app.globalData.phone_bill_recharge_type = false;
        if (res.confirm) {
          wx.navigateTo({
            url: extinfo.path + '?' + extinfo.option
          })
        }            
      }
    })
    break;
  case "signContract":
    return wx.showModal({
      content: '您有合同未签署完成，请前往签署合同',
      complete: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/packageH/signPage/contractList/contractList?status=1&cid=' + extinfo.cid
          });
        } else if (res.cancel) {
          wx.redirectTo({
            url: '/packageG/index/index'
          });
        }
      }
    })
    break;
  }
  
  if(extinfo?.option) path = path + '?' + extinfo.option;
  if(path) wx.redirectTo({url: path});
}

function getRouteData(){
  var pages = getCurrentPages(); //获取加载的页面
  var currentPage = pages[pages.length - 1]; //获取当前页面的对象
  let routeData = currentPage.route;
  return routeData||'';
}

// 判断当前页面是否需要进入邀请页，以及判断用户是否已经填写过邀请人和绑定手机
// 如果未填写或未绑定，则会跳转到邀请页。
function bindInviter(data) {
  if (data.invite_page !== 1) {
    return Promise.resolve(); //没有开启，resolve
  }
  if (data.is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  let _href = getRouteData();
  const ignoredPages = ["packageC/member/visit/Inviter/Inviter", 'packageC/member/visit/InputVisit/InputVisit', "packageA/member/editmobile/editmobile", "pages/login/login"]; // 忽略某些页面，不需要进入邀请页或者已在邀请相关页面内
  const requiresInvitation = !ignoredPages.some((page) => _href == page);
  if (_href == 'packageC/member/visit/Inviter/Inviter' || !requiresInvitation) {
    return Promise.reject({type: 'active',name: '填写邀请码'});
  }
  // 判断用户是否已有邀请码
  if ((data.is_invite !== 1) || data.invite_mobile !== 1) {
    return Promise.reject({type: 'bindInviter',name: '填写邀请码',icon: 'icon-fontclass-yaoqingma',color: '#FF3835'});// 需要跳转到邀请页面
  }
  return Promise.resolve();
}

// 绑定手机
async function bindMobile(data) {
  let { is_bind_mobile, bind_mobile_page } = data;
  if (data.is_login !== 1) {
   return Promise.resolve(); // 判断用户是否已登录
 }
  if (is_bind_mobile === 0) {
    return Promise.resolve();
  }
  let _href = _activePageURL;
  if (_href == 'packageA/member/editmobile/editmobile') {
    return Promise.reject({type: 'active',name: '绑定手机'});
  }
  if (_href == 'packageH/signPage/personBank/personBank') {
    return Promise.reject({type: 'bindMobile',name: '绑定手机',icon: 'icon-verification_phone',color: '#377BFE'});
  }
  let bindMobilePageFn = (item, url, extinfo) => {
    // 判断是否符合场景页面
    if (_href.indexOf(url) > -1) {
      return Promise.reject({type: 'bindMobile',name: '绑定手机',icon: 'icon-verification_phone',color: '#377BFE',extinfo: extinfo});
    }
  };
  if (is_bind_mobile == 1) {
    //跳转绑定手机页面
    return Promise.reject({type: 'bindMobile',name: '绑定手机',icon: 'icon-verification_phone',color: '#377BFE'});
  } else if (is_bind_mobile == 2) {
   
    for (const item of bind_mobile_page) {
      switch (item) {
      case "member_center":
        await bindMobilePageFn(item, "packageG/member_v2/member_v2", { option: 'fromApp=2'});
        break;
      case "goods_detail":
        await bindMobilePageFn(item, "packageA/detail_v2/detail_v2",{option: 'fromApp=1'});
        break;
      case "promotion_center":
        await bindMobilePageFn(item, "packageG/pages/member/extension/extension",{option: 'fromApp=4'});
        break;
      }
    }
    return Promise.resolve();
  }
}

// 实名认证
function bindRealName(data) {
   if (data.is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  // 定义排除的 URL。
  const excludedUrls = ["packageH/signPage/personBank/personBank", "packageH/signIndexPlu/signCompany/signCompany", 'packageH/signPage/signCompany/signCompany', "packageD/buy/orderPay/orderPay"];
  // 检查当前 URL 是否被排除。
  const currentUrl = getRouteData();
  if (excludedUrls.some((url) => currentUrl == url)) {
    return Promise.reject({type: 'active',name: '实名认证'});
  }
  // 检查实名认证插件是否开启并且需要进行认证。
  const isOpen = data.real_name_auth_is_open === 1;
  const needsAuth = data.is_auth !== 1 && data.real_name_auth_scene?.length > 0;
  if (isOpen && needsAuth) {
    if(data.real_name_auth_scene.indexOf("1") > -1 && currentUrl !== 'packageH/signPage/personBank/personBank') {
      return Promise.reject({type: 'bindRealName',name: '实名认证',icon: 'icon-fontclass-wdeguanzhu',color: '#377BFE',extinfo: {option: 'from=bindRealName' }});
    }
    // 定义需要实名认证的场景 URL。
    const scenarioUrls = {
      2: ["packageA/member/withdrawal/withdrawal"],
      3: ["packageC/video_goods/videoAgreement/videoAgreement", "packageC/video_goods/releaseVideo/releaseVideo"],
      4: ["packageC/micro_communities/microRelease/microRelease"],
      5: ["packageG/pages/member/extension/extension"],
      6: ["packageA/member/supplier/supplier"],
      7: ["packageA/member/storeApply/storeApply"],
      8: ["packageA/member/storeApply/storeApply"],
      9: ["packageD/directSeeding/anchorApply/anchorApply"],
      13: ["packageJ/anytime_service/my/role_apply_for/enterprise/enterprise","packageJ/anytime_service/my/role_apply_for/promulgator/promulgator","packageJ/anytime_service/my/role_apply_for/master_worker/master_worker"]
    };
    let isPageOtions = (scene) => {
      // 判断当前页面参数是否符合场景值页面
      let vaule = true;
      switch (scene) {
        case 7:
          vaule = JSON.stringify(currentPage.options) == "{}";// 酒店申请跟门店一样路径，但参数不一样
          break;
        case 8:
          vaule = currentPage.options.name == "hotelApply";// 酒店;
          break;
        case 13:
          let _anytimePromulagator = routeData == "packageJ/anytime_service/my/role_apply_for/promulgator/promulgator" && currentPage.options.role==1; //供需平台-发布者申请
          let _anytimeWork = routeData == "packageJ/anytime_service/my/role_apply_for/master_worker/master_worker" && currentPage.options.apply_type==1; // 供需平台-技能师傅申请
          let _anytimeEnterprise = routeData == "packageJ/anytime_service/my/role_apply_for/enterprise/enterprise";//供需平台-企业申请
          vaule = _anytimePromulagator||_anytimeWork||_anytimeEnterprise;
          break;
        default:
          break;
      }
      return vaule;
    };
    // 检查当前 URL 是否匹配任何场景 URL。
    const needsRealName = data.real_name_auth_scene.some((scene) => {
      const urls = scenarioUrls[scene] ?? [];
      let urlsOpt = isPageOtions(scene);
      return urls.some((url) => _activePageURL == url && urlsOpt);
    });
    if (needsRealName) {
      // 需要进行实名认证，跳转至实名认证页面。
      wx.setStorageSync("real_name_redirect", _activePageURL);
      return Promise.reject({type: 'bindRealName',name: '实名认证',icon: 'icon-fontclass-wdeguanzhu',color: '#377BFE',extinfo: {option: 'from=bindRealName' }});
    }
  }
  // 实名插件未开启或已实名认证过，直接下一步
  return Promise.resolve();
}

// 绑定地址
function setAddress({ is_login, bind_address: { bind_address_type, bind_address_page, is_bind_address } }) {
  if (is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  if(is_bind_address === 1) return Promise.resolve();
  let currentUrl = getRouteData();
  const excludedUrls = ["packageD/member/addressList/addressList", "packageD/member/addressAdd_v2/addressAdd_v2", "pages/login/login"];//当前链接符合该数组条件，拦截但不处理
  if (excludedUrls.some(url => currentUrl == url)) {
    return Promise.reject({type: 'active',name: '绑定地址'});
  }

  const pageUrls = {
    member_center: "packageG/member_v2/member_v2",
    goods_detail: ["packageA/detail_v2/detail_v2"],
    promotion_center: "packageG/pages/member/extension/extension",
  };
  const isBindPage = (pageUrl) => (Array.isArray(pageUrl) ? pageUrl.some((url) => _activePageURL.includes(url)) : _activePageURL.includes(pageUrl));
  const isBindAddressPage = bind_address_type === 2 && bind_address_page.some((pageName) => isBindPage(pageUrls[pageName]));

  if(bind_address_type === 1) return Promise.reject({type: 'setAddress',name: '绑定地址',icon: 'icon-icon_location',color: '#29D99F'});//全局绑定
  if(isBindAddressPage) return Promise.reject({type: 'setAddress',name: '绑定地址',icon: 'icon-icon_location',color: '#29D99F'});//指定页面
  return Promise.resolve();
}

// 默认上传视频（需要上传过视频才可进入视频）
function uploadVideo(data){
  if (data.is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  let currentUrl = getRouteData();
  if (currentUrl == 'packageC/video_goods/releaseVideo/releaseVideo') {
    return Promise.reject({type: 'active',name: '发布视频'});
  }
  if(data?.need_video && currentUrl !== 'packageC/video_goods/releaseVideo/releaseVideo'){
    return Promise.reject({type: 'uploadVideo',name: '发布视频',icon: 'icon-fontclass-ship',color: '#29D99F',extinfo: {option: 'from=validate'}});
  }
  return Promise.resolve();
}

// 新客下单
function levelCompel(data) {
  if (data.is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  let currentUrl = getRouteData();
  const excludedUrls = ["packageJ/levelCompel/levelCompel", "packageD/buy/orderPay/orderPay","packageI/pay_back/pay_back" ,"pages/login/login"];//当前链接符合该数组条件，拦截但不处理
  if (excludedUrls.some(url => currentUrl == url)) {
    return Promise.reject({type: 'active',name: '新客下单'});
  }
  let isLevel = data?.is_level_compel && data.is_level_compel == 1;
  if(isLevel){
    return Promise.reject({type: 'levelCompel',name: '新客下单',icon: 'icon-qt_button_groupbbuy',color: '#29D99F'});
  }
  return Promise.resolve();
}

// 话费充值 -- #19217
function phoneBillRecharge(data){
  if (data.is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  let currentUrl = getRouteData();
  if (currentUrl == "/packageJ/phoneBillRecharge/recharge_phone_bill/recharge_phone_bill") {
    return Promise.reject({ type: "active", name: "绑卡开卡" });
  }
  if (!_app.globalData.phone_bill_recharge_type) {
    return Promise.resolve();//已经弹过
  }
  // 满足phone_bill_recharge_member条件而且是在登陆后触发
  if (data && data.phone_bill_recharge_member && data.phone_bill_recharge_member.status == 1 && data.is_login == 1) {
    let _phone_bill_recharge_data = { type: "phoneBillRecharge", name: "绑卡开卡", icon: "icon-qt_button_groupbbuy", color: "#29D99F" };
    _phone_bill_recharge_data.extinfo.content = data.phone_bill_recharge_member.tips;
    if(data.phone_bill_recharge_member.type == 'copy'){
      _phone_bill_recharge_data.extinfo.path = '/packageJ/phoneBillRecharge/recharge_phone_bill/recharge_phone_bill';
      _phone_bill_recharge_data.extinfo.option = 'url=' + encodeURIComponent(data.phone_bill_recharge_member.url) +'&card_type=' + data.phone_bill_recharge_member.card_type;
    }else{
      _phone_bill_recharge_data.extinfo.path = '/packageI/web-view/h5View';
      _phone_bill_recharge_data.extinfo.option = 'diyUrl='+encodeURIComponent(data.phone_bill_recharge_member.url);
    }
    return Promise.reject(_phone_bill_recharge_data);
  }
  return Promise.resolve();
}

// #32329 如用户有待签署的合同时，无法进入会员中心和推广中心，弹出提示,点击“去签署”，则跳转到待签署的合同列表。
function signContract(data) {
  if (data.is_login !== 1) {
    return Promise.resolve(); // 判断用户是否已登录
  }
  const excludedUrls = ["packageH/signPage/signIndex/signIndex", "packageH/signPage/contractList/contractList", "packageH/signPage/signPage"]; //当前链接符合该数组条件，拦截但不处理
  let currentUrl = getRouteData();
  if (excludedUrls.some(url => currentUrl == url)) {
    return Promise.reject({type: 'active',name: '合同签署'});
  }
  // 定义需要签署的场景
  const needSignUrls = ["packageG/member_v2/member_v2", "packageG/pages/member/extension/extension",'packageG/missionCenter/missionCenter'];
  // 检查当前 URL 是否匹配到指定场景 URL。
  const isNeedSignUrls = needSignUrls.some(url => currentUrl == url);

  if (isNeedSignUrls && data?.shop_contract && data?.shop_contract.member_center_status && data?.shop_contract.contract_id) {
    return Promise.reject({ type: "signContract", name: "合同签署", icon: "icon-fontclass-gerenyinzhang", color: "#ee0a24", extinfo: {cid: data.shop_contract.cid}});
  }
  return Promise.resolve();
}

export { unfinishedTaskFn,redirectToPage };